package com.h3c.nem.utils;

import com.eos.common.util.DateUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static String dateToWeek(Date date) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        int i = instance.get(Calendar.DAY_OF_WEEK) - 1;
        return weekDays[i];
    }

    /**
     * 一周的最后一天
     * @param date
     * @return
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek + 7);
        return DateUtils.dateAddSeconds(cal.getTime(), -1);
    }

    /**
     * 获取当天开始时间
     */
    public static Date getDateBegin(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 一个月的最后一天
     * @param date
     * @return
     */
    public static Date getLastDayOfMonth(Date date) {
        try {
            return DateUtils.minDateOfMonth(date);
        } catch (Exception e) {
            throw new AppBusinessException("时间转换错误");
        }
    }

    /**
     * 由出生日期获得年龄
     */
    public static int getAge(Date birthDay) {
        try {
            int age = 0;
            Calendar cal = Calendar.getInstance();
            if (cal.before(birthDay)) {
                return age;
            }
            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH);
            int dayNow = cal.get(Calendar.DAY_OF_MONTH);
            cal.setTime(birthDay);

            int yearBirth = cal.get(Calendar.YEAR);
            int monthBirth = cal.get(Calendar.MONTH);
            int dayBirth = cal.get(Calendar.DAY_OF_MONTH);
            //年相减
            age = yearNow - yearBirth;
            //判断月份
            if (monthNow <= monthBirth) {
                if (monthNow == monthBirth) {
                    //判断天
                    if (dayNow < dayBirth) {
                        age--;
                    }
                } else {
                    age--;
                }
            }
            return age;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取String
     * @param date
     * @return
     */
    public static String getDateStr(Date date) {
        return dateFormat.format(date);
    }

}
